package com.example.administrator.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    EditText mEtUserName;
    TextView mTvMsg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEtUserName = findViewById(R.id.et_username);
        mTvMsg = findViewById(R.id.tv_msg);
    }

    public void login(View view) throws IOException {
        String username = mEtUserName.getText().toString();

        try{

        FileOutputStream fileOutputStream = openFileOutput("2.txt",MODE_PRIVATE);
        byte[] msg = username.getBytes();
        fileOutputStream.write(msg);
        fileOutputStream.close();
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
        }

    }

    public void read(View view) {
        try {
            //获取输入字节
            FileInputStream fileInputStream
                    = openFileInput("2.txt");
            //fileInputStream.available()输入流中的有效字节数
            byte[] bytes = new byte[fileInputStream.available()];
            //读取文件数据到字节数组
            fileInputStream.read(bytes);
            //关闭输入流
            fileInputStream.close();
            //将字节信息转换成字符串
            String msg = new String(bytes);
            //将字节信息呈现到TextView
            mTvMsg.setText(msg);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}